import { Notification } from "element-ui";

let socket = null;
let reconnectTimer = null;
let heartbeatTimer = null;
const timeout = 30000; // 30秒心跳间隔
const reconnectDelay = 5000; // 5秒重连间隔

// 初始化WebSocket  在initWebSocket函数中添加异地登录检测
const initWebSocket = () => {
  const token = localStorage.getItem('token');
  if (!token) {
    Notification.error({ title: "错误", message: "未获取到用户Token" });
    return;
  }

  if (socket) closeWebSocket();

  const wsUrl = `ws://10.10.10.88:9999/outpatient/ws?token=${token}`;
  socket = new WebSocket(wsUrl);

  socket.onopen = () => {
    console.log('WebSocket连接已建立');
    startHeartbeat();
    window.dispatchEvent(new Event('websocket-open'));
  };

  socket.onmessage = (e) => {
	const message = JSON.parse(e.data);
    console.log('收到WebSocket消息:', message);
    resetHeartbeat();
    try {
      
      // 新增：检查消息类型为异地登录（假设type=4表示异地登录）
		if (message.type === 4) {
		  Notification({
			title: "安全警告",
			message: "您的账号已在其他地方登录，您将被强制退出",
			type: "error",
			duration: 0, // 不自动关闭
			showClose: false
		  });
		  
		  // 5秒后强制退出
		  setTimeout(() => {
			localStorage.clear();
			window.location.href = "#/login";
		  }, 5000);
		}
      // 新增：检查消息类型是否为3，如果是则显示通知
      if (message.type === 3) {
        Notification({
          title: "系统通知",
          message: message.data || "您有一条新消息",
          type: "warning",
		  duration: 4800
        });
      }
      
      window.dispatchEvent(new CustomEvent('websocket-message', { detail: message }));
    } catch (error) {
      console.error('消息解析失败:', error);
    }
  };

  socket.onclose = (e) => {
    console.log('WebSocket连接关闭');
    reconnect();
    window.dispatchEvent(new Event('websocket-close'));
  };

  socket.onerror = (error) => {
    console.error('WebSocket错误:', error);
    reconnect();
    window.dispatchEvent(new CustomEvent('websocket-error', { detail: error }));
  };
};

// 启动心跳检测
const startHeartbeat = () => {
  let sendData = {
    type:'1',
    data:{}
  }
  heartbeatTimer = setInterval(() => {
    if (socket?.readyState === WebSocket.OPEN) {
      sendMessage(sendData);
    }
  }, timeout);
};

// 重置心跳检测
const resetHeartbeat = () => {
  clearInterval(heartbeatTimer);
  startHeartbeat();
};

// 重连机制
const reconnect = () => {
  if (reconnectTimer || !socket) return;
  
  reconnectTimer = setTimeout(() => {
    console.log('尝试重新连接...');
    //initWebSocket();
    reconnectTimer = null;
  }, reconnectDelay);
};

// 发送消息
const sendMessage = (message) => {
  if (socket?.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify(message));
  } else {
    console.error('WebSocket未连接，消息发送失败:', message);
  }
};

// 关闭连接
const closeWebSocket = () => {
  if (socket) {
    socket.close();
    socket = null;
  }
  clearInterval(heartbeatTimer);
  clearTimeout(reconnectTimer);
};

export default {
  initWebSocket,
  sendMessage,
  closeWebSocket
};